package com.baizhi.cmfz.controller;

import cn.hutool.core.lang.UUID;
import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.entity.Articel;
import com.baizhi.cmfz.service.ArticelService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/articel")
public class ArticelControllrt {

	@Autowired
	private ArticelService articelService;

	/**
	 * @RequiresPermissions("aritcle:show") 配置只有拥有这个权限的管理员才可以访问的方法
	 * @LogAnnotation(value = "查询文章的分页信息",type = "select") 用于生成日志记录
	 * @RequestMapping("/selectArticelPage") 配置方法的访问路径
	 *
	 * @param page 当前页码
	 * @param limit 每页显示的行数
	 * @param name 模糊查询时需要的文章名
	 * @return 返回符合条件的map集合
	 */
	@RequiresPermissions("aritcle:show")
	@LogAnnotation(value = "查询文章的分页信息",type = "select")
	@RequestMapping("/selectArticelPage")
	public Map selectArticelPage(int page,int limit,String name){
		return articelService.selectArticelPage(page, limit, name);
	}



	@RequiresPermissions("aritcle:insert")
	@LogAnnotation(value = "添加文章",type = "insert")
	@RequestMapping("/insertArticel")
	public Map insertArticel(MultipartFile file , Articel articel , HttpServletRequest request) throws IOException {
//		文件上传+新的文件名
		String s = fileUpload(file, request);
		articel.setArticelImage("img/"+s);
		System.out.println(articel);
		return articelService.insertArticel(articel);
	}



	@LogAnnotation(value = "修改文章信息",type = "update")
	@RequestMapping("/updateArticel")
	public Map updateArticel(MultipartFile file,Articel articel,HttpServletRequest request) throws IOException {
		String s = null;
		if(!"".equals(file.getOriginalFilename()) && file.getOriginalFilename() != null){
			s = fileUpload(file, request);
			articel.setArticelImage("img/"+s);
		}else{
			articel.setArticelImage(s);
		}
		Map map = articelService.updateArticel(articel);
		return map;
	}



	@LogAnnotation(value = "查询单个文章的信息",type = "select")
	@RequestMapping("/selectById")
	public Map selectById(int id){
		return articelService.selectById(id);
	}


	@LogAnnotation(value = "删除文章信息",type = "delete")
	@RequestMapping("/deleteArticel")
	public Map deleteArticel(int id){

		return articelService.deleteArticel(id);
	}


	private String  fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
//		进行文件上传的操作
//		获取文件的文件名
		String filename = file.getOriginalFilename();
//		创建新的文件名
		String newName = UUID.fastUUID().toString().replace("-", "")+"_"+filename;
//		获取文件在项目中的位置
		String img = request.getServletContext().getRealPath("img");
//		上传文件
		file.transferTo(new File(img+"/"+newName));
		return newName;

	}
}
